package com.qersoft.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qersoft.entity.Paper;
import com.qersoft.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/papers")
public class PaperController {

    @Autowired
    private PaperService paperService;

    // 新增试卷接口（试卷保存功能）
    @PostMapping("/save")
    public ResponseEntity<String> savePaper(@RequestBody Paper paper) {
        boolean result = paperService.savePaper(paper);
        if (result) {
            return new ResponseEntity<>("试卷保存成功", HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>("试卷保存失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    // 使用DeleteMapping注解表示接收DELETE请求，通过PathVariable获取要删除试卷的id
    @DeleteMapping("/deletebyid/{id}")
    public ResponseEntity<String> deletePaper(@PathVariable Long id) {
        boolean result = paperService.deletePaperById(id);
        if (result) {
            return new ResponseEntity<>("试卷删除成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("试卷删除失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据试卷ID查询试卷接口
    @GetMapping("/getbyid/{id}")
    public ResponseEntity<Paper> getPaper(@PathVariable Long id) {
        Paper paper = paperService.getPaperById(id);
        if (paper!= null) {
            return new ResponseEntity<>(paper, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    // 根据试卷标题模糊查询试卷接口
    @GetMapping("/getbytitle")
    public ResponseEntity<List<Paper>> getPapersByTitle(@RequestParam(required = false) String title) {
        List<Paper> papers;
        if (title!= null) {
            papers = paperService.getPapersByTitle(title);
        } else {
            papers = paperService.getAllPapers();
        }
        return new ResponseEntity<>(papers, HttpStatus.OK);
    }

    // 分页查询试卷接口
    @GetMapping("/getbypage")
    public ResponseEntity<IPage<Paper>> getPapersByPage(@RequestParam(defaultValue = "1") int currentPage,
                                                        @RequestParam(defaultValue = "10") int pageSize) {
        IPage<Paper> papers = paperService.getPapersByPage(currentPage, pageSize);
        return new ResponseEntity<>(papers, HttpStatus.OK);
    }
    //改试卷的相关信息。
    @PutMapping("/update")
    public ResponseEntity<String> updatePaper(@RequestBody Paper paper) {
        boolean result = paperService.updatePaper(paper);
        if (result) {
            return new ResponseEntity<>("试卷更新成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("试卷更新失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}